//
//  LXRPlaceholderTextView.m
//  01- 百思不得姐
//
//  Created by mac on 16/7/1.
//  Copyright © 2016年 mac. All rights reserved.

//拥有占位文字功能的TextView

#if 0
1.setNeedsDisplay方法 : 会在恰当的时刻自动调用drawRect:方法
2.setNeedsLayout方法: 会在恰当的时刻调用layoutSubviews方法
#endif

#import "LXRPlaceholderTextView.h"

@interface LXRPlaceholderTextView()
/** 占位文字Lable */
@property(nonatomic,weak)UILabel* placeholderLable;

@end

@implementation LXRPlaceholderTextView

-(UILabel *)placeholderLable{
    if (!_placeholderLable) {
        UILabel* placeholderLable = [[UILabel alloc]init];
        placeholderLable.numberOfLines = 0;
        placeholderLable.x = 4;
        placeholderLable.y = 7;
        [self addSubview:placeholderLable];
        _placeholderLable = placeholderLable;
    }
    return _placeholderLable;
}

#pragma mark - 代码创建LXRPlaceholderTextView初始化设置
-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        //默认文字字体
        self.font = LXRTagFont;
        //默认文字颜色
        self.placeholderColer = [UIColor grayColor];
        //UITextView继承自UIScrollView,UIScrollView有弹框属性(垂直弹簧属性)
        self.alwaysBounceVertical = YES;
        //监听文字改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}
#pragma mark - 监听文字改变
-(void)textDidChange{
    //只要有文字,就隐藏占位文字Lable
    self.placeholderLable.hidden = self.hasText;
}
#pragma mark - 更改占位文字的尺寸
-(void)layoutSubviews{
    [super layoutSubviews];
/**方法1:计算占位文字Size*/
//    //Lable的最大Size
//    CGSize maxSize = CGSizeMake(self.width - 2*self.placeholderLable.x, MAXFLOAT);
//    //计算占位文字的Size
//    self.placeholderLable.size = [self.placeholder boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.font} context:nil].size;
    
/**方法2:计算占位文字Size*/
    
    self.placeholderLable.width = self.width - 2 * self.placeholderLable.x;
    [self.placeholderLable sizeToFit];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - 重写setter
/** placeholder */
-(void)setPlaceholder:(NSString *)placeholder{
    _placeholder = [placeholder copy];
    self.placeholderLable.text = placeholder;
    [self setNeedsLayout];
}
/** placeholderColer */
-(void)setPlaceholderColer:(UIColor *)placeholderColer{
    _placeholderColer = placeholderColer;
    self.placeholderLable.textColor = placeholderColer;
}
/** font */
-(void)setFont:(UIFont *)font{
    [super setFont:font];
    self.placeholderLable.font = font;
    [self setNeedsLayout];
}
/** text */
-(void)setText:(NSString *)text{
    [super setText:text];
    [self textDidChange];
}
/** attributedText */
-(void)setAttributedText:(NSAttributedString *)attributedText{
    [super setAttributedText:attributedText];
    [self textDidChange];
}
@end
